#!/bin/bash
#
# Transport that uses the cp(1) command to copy local files
#
# Author:   Dr. Mike Murphy (mmurphy2@coastal.edu)
# Revision: 20 November 2013
#
#   Copyright 2012-2013 Coastal Carolina University
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
#


## p_transport_cp_can_download <url>
##
## Determines if the cp transport can download <url>. Returns 0 if the
## transport is able to handle the <url>, non-zero otherwise.
##
function p_transport_cp_can_download() {
	local status=0
	local chk=
	local filename=
	
	which cp > /dev/null 2>&1
	status=$?
	
	if [[ ${status} -eq 0 ]]; then
		# Have the cp command: check to see if this is a true URL
		chk=$(echo "$1" | grep '://')
		if [[ -n "${chk}" ]]; then
			# Check for file://
			chk=$(echo "$1" | grep '^file://')
			if [[ -z "${chk}" ]]; then
				# Probably can't handle this with cp
				status=1
			else
				# Get the absolute path
				filename=$(echo "$1" | sed s~'^file://'~~)
			fi
		else
			# Not a URL: check to be sure we have an absolute path
			chk=$(echo "$1" | grep ^/)
			if [[ -z "${chk}" ]]; then
				# URL wasn't resolved to an absolute path first, so no go
				status=1
			else
				filename="$1"
			fi
		fi
		
		# One final test: if we do have something that looks like a file,
		# make sure it actually exists and is a readable file (not a directory)
		if [[ -n "${filename}" ]]; then
			if [[ -r "${filename}" ]]; then
				if [[ -d "${filename}" ]]; then
					# Can only copy a file, not a directory
					status=1
				fi
			else
				# unreadable
				status=1
			fi
		fi
	fi
	
	return ${status}
}


## p_transport_cp_download <url> <output file> <user agent>
##
## Copies a file from <url> to <output file>. If <output file> is the special
## name "-", cat's the file at <url> instead. The <user agent> is ignored.
## Returns 0 on success, non-zero if an error occurs.
##
function p_transport_cp_download() {
	local status=0
	local url=$(echo "$1" | sed s~'^file://'~~)
	
	if [[ "$2" == "-" ]]; then
		cat "${url}"
		status=$?
	else
		cp "${url}" "$2"
		status=$?
	fi
	
	return ${status}
}
